<script setup>
import { ref } from "vue";
import { useTokenStore } from "@/stores/token.js";
import useUserInfoStore from "@/stores/userInfo.js";
import { resetPasswordService } from "@/api/user.js";
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router';

const tokenStore = useTokenStore();
const userInfoStore = useUserInfoStore();
const router = useRouter();

const rePasswordData = ref({
  id: userInfoStore.userInfo.userId,
  password: '',
  rePassword: ''
});

const isPassword = () => {
  return rePasswordData.value.password === rePasswordData.value.rePassword;
};

const validatePassword = (value) => {
  // 检查密码长度
  if (value.length < 8 || value.length > 16) {
    return '密码长度必须在8到16位之间';
  }

  // 定义正则表达式检查密码特性
  const hasUpperCase = /[A-Z]/.test(value);
  const hasLowerCase = /[a-z]/.test(value);
  const hasDigit = /\d/.test(value);
  const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(value);

  const types = [hasUpperCase, hasLowerCase, hasDigit, hasSpecialChar].filter(Boolean).length;

  if (types < 3) {
    return '密码必须包含大小写字母、数字和特殊符号中的至少三种';
  }

  return '';
};

const rePassword = async () => {
  if (!isPassword()) {
    ElMessage.error('密码不一致');
    return;
  }

  const validationMessage = validatePassword(rePasswordData.value.password);
  if (validationMessage) {
    ElMessage.error(validationMessage);
    return;
  }


    let result = await resetPasswordService(rePasswordData.value);
    if (result && result.message) {
      ElMessage.success(result.message);
    } else {
      ElMessage.success('修改成功');
    }
    tokenStore.removeToken();
    userInfoStore.removeUserInfo();
    await router.push('/login');

};

const rules = {
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { required: true, message: '请输入密码', trigger: 'focus' }
  ],
  rePassword: [
    {required: true, message: '再次输入密码', trigger: 'blur'},
    {required: true, message: '再次输入密码', trigger: 'focus'},
    {
      validator: (rule, value, callback) => {
        if (!isPassword()) {
          callback(new Error('密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (!isPassword()) {
          callback(new Error('密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'focus'
    }
  ]
};
</script>

<template>
  <el-form ref="formRef" :model="rePasswordData" :rules="rules" label-width="150px">
    <el-form-item label="密码" prop="password">
      <el-input v-model="rePasswordData.password" show-password style="width: 50%"/>
    </el-form-item>
    <el-form-item label="再次输入密码" prop="rePassword">
      <el-input v-model="rePasswordData.rePassword" show-password style="width: 50%"/>
    </el-form-item>
  </el-form>
  <el-button type="primary" @click="rePassword">重置密码</el-button>
</template>

<style scoped>
</style>
